import threading

from xtquant import xtdata

from module_stock.service.trade_executor import get_trade_executor


class XtDataSubscriptionManager():
    def __init__(self):
        super().__init__()
        print("XtDataSubscriptionManager init")
        self.subscriptions = {}  # {stock_code: seq}
        # 绑定回调函数
        self.callback = self.market_callback

    def market_callback(self, data):
        """行情回调函数 - 发布行情数据事件"""
        get_trade_executor().on_tick_data(data)

    def add_subscriptions(self, stock_codes, period="tick"):
        """批量添加股票订阅"""
        for stock_code in stock_codes:
            self.add_subscription(stock_code, period)

    def add_subscription(self, stock_code, period="tick"):
        """添加新股票订阅"""
        if stock_code in self.subscriptions:
            print(f"添加股票订阅-订阅已存在: {stock_code}={self.subscriptions[stock_code]}")
            return self.subscriptions[stock_code]
        # 创建订阅并记录序列号
        seq = xtdata.subscribe_quote(stock_code=stock_code, period=period, callback=self.market_callback)
        self.subscriptions[stock_code] = seq
        if seq == -1:
            print(f"添加股票订阅-失败: {stock_code}={seq}")
        print(f"添加股票订阅-成功: {stock_code}={seq}")
        return seq

    def remove_subscription(self, stock_code):
        """取消已有订阅"""
        if stock_code not in self.subscriptions:
            print(f"取消股票订阅-无此订阅: {stock_code}")
            return False

        seq = self.subscriptions[stock_code]
        xtdata.unsubscribe_quote(seq)
        del self.subscriptions[stock_code]  # 添加此行清理记录
        print(f"取消股票订阅: {stock_code} [订阅号: {seq}]")
        return True

    def remove_all_subscription(self):
        """停止所有订阅"""
        subscriptions_copy = self.subscriptions.copy()
        for stock_code in subscriptions_copy:
            self.remove_subscription(stock_code)
        print("所有股票订阅已取消")


_xtdata_instance = None
# 线程锁，确保多线程安全
_instance_lock = threading.Lock()


def xtdata_subscription_manager():
    """工厂函数，返回单例实例"""
    global _xtdata_instance
    with _instance_lock:
        if _xtdata_instance is None:
            _xtdata_instance = XtDataSubscriptionManager()
    return _xtdata_instance
